package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseTest;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Autowired
    ShoppingCartService shoppingCartService;


    @GetMapping("list")
    public R<List<ShoppingCart>> list(){
        Long userId = BaseTest.get();
        List<ShoppingCart> list = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
        return R.success(list);
    }
    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        Long userId = BaseTest.get();
        ShoppingCart one = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId)
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .one();
        if (one!=null){
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
            return R.success(one);
        }
        else {
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }
    }
    @DeleteMapping("clean")
    public R<String> clean(){
        Long userId = BaseTest.get();
        shoppingCartService.update().eq("user_id",userId).remove();
        return R.success("删除成功");
    }

}
